#pragma once
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include <cstdio>
#include <fcntl.h>
#include <cstdlib>
#include <string.h>

#define ERR_EXIT(m)\
do\
{\
    perror(m);\
    exit(EXIT_FAILURE);\
}while(0);

#define PATH "."
#define FILENAME "CHANNEL"

class NameFifo
{
public:
    NameFifo(std::string path, std::string name)
    :_path(path),
     _name(name),
     _fd(-1)
    {
        _pathName = _path + "/" + _name;
    }

    void makeFifo()
    {
        umask(0);
        int n = mkfifo(_pathName.c_str(), 0666);
        if(n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "mkfifo success" << std::endl;
        }
    }

    void OpenForRead()
    {
        _fd = open(_pathName.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open fifo for read");
        }
        std::cout << "open fifo success" << std::endl;
    }

    void OpenForWrite()
    {
        _fd = open(_pathName.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open fifo for write");
        }
        std::cout << "open fifo success" << std::endl;
    }

    void Read()
    {
        char buf[1024];
        memset(buf, 0, sizeof(buf));
        ssize_t n = read(_fd, buf, sizeof(buf) - 1);
        if(n < 0)
        {
            ERR_EXIT("read error");
        }
        else if(n == 0)
        {
            std::cout << "server quit! me too!" << std::endl;
            sleep(1);
        }
        buf[n] = 0;
        std::cout << "Client Say# " << buf << std::endl;
    }

    void Write()
    {
        std::string message;
        int cnt = 1;
        pid_t id = getpid();
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        message += (", message number: " + std::to_string(cnt++) + ", [" + std::to_string(id) + "]");
        write(_fd, message.c_str(), message.size());
    }

    void fifoQuit()
    {
        int n = unlink(_pathName.c_str());
        if (n == 0)
        {
            ERR_EXIT("unlink");
        }
        else
        {
            std::cout << "remove fifo failed" << std::endl;
        }
    }
    

    void Close()
    {
        if(_fd > 0)
        {
            close(_fd);
            std::cout << "close fd";
        }
    }

    ~NameFifo()
    {}
private:
    std::string _path;
    std::string _name;
    std::string _pathName;
    int _fd;
};





